<template>
  <div class="excel-handler">
    <!-- 导入按钮 -->
    <el-button 
      v-if="showImport"
      class="excel-button"
      @click="openImportDialog"
      style="margin-left: 25px"
    >
      {{ importButtonText || 'excel导入' }}
    </el-button>

    <!-- 导出按钮 -->
    <el-button 
      v-if="showExport"
      :loading="exporting"
      class="excel-button"
      @click="handleExport"
    >
    {{ exportButtonText || 'excel导出' }}
    </el-button>

    <!-- 导入弹窗 -->
    <el-dialog
      v-model="importDialogVisible"
      title="员工导入"
      width="520px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      class="import-dialog"
    >
      <el-upload
        class="upload-area"
        :auto-upload="true"
        :show-file-list="false"
        :http-request="handleFileUpload"
        accept=".xlsx, .xls"
        drag
      >
        <div class="upload-content">
          <el-icon :size="40" color="#909399"><Upload /></el-icon>
          <div class="upload-text">
            <p>将文件拖到此处或<em>点击上传</em></p>
            <p class="upload-tip">支持扩展名：.xls, .xlsx</p>
          </div>
        </div>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="importDialogVisible = false">取 消</el-button>
          <el-button 
            type="primary" 
            @click="downloadTemplate"
          >
            下载导入模板
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, defineProps} from 'vue'
import { ElMessage } from 'element-plus'
import { Upload } from '@element-plus/icons-vue'
import * as XLSX from 'xlsx'
import type { ExcelHandlerProps, ExcelHandlerEmits } from '@/types/components'




const props = defineProps<ExcelHandlerProps>()
console.log(props);

const emit = defineEmits<ExcelHandlerEmits>()

const importing = ref(false)
const exporting = ref(false)
const importDialogVisible = ref(false)

// 打开导入弹窗
const openImportDialog = () => {
  importDialogVisible.value = true
}

// 处理文件上传
const handleFileUpload = async (options: any) => {
  const file = options.file
  if (!file) return

  importing.value = true
  try {
    const data = await readExcelFile(file)
    const processedData = props.importHandler ? await props.importHandler(data) : data
    emit('import-success', processedData)
    ElMessage.success('导入成功')
    importDialogVisible.value = false
  } catch (error: any) {
    emit('import-error', error)
    ElMessage.error(error.message || '导入失败')
  } finally {
    importing.value = false
  }
}

// 下载模板
const downloadTemplate = () => {
  if (!props.templateUrl) {
    ElMessage.warning('模板下载地址未配置')
    return
  }

  // 创建一个隐藏的a标签来下载文件
  const link = document.createElement('a')
  link.href = props.templateUrl
  link.download = '导入模板.xlsx'
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

// 处理Excel导出
const handleExport = async () => {
  if (!props.exportData || !props.exportColumns) {
    ElMessage.warning('导出配置不完整')
    return
  }

  exporting.value = true
  try {
    let exportData = props.exportData
    if (props.exportHandler) {
      exportData = await props.exportHandler(exportData)
    }

    const worksheet = XLSX.utils.json_to_sheet(
      exportData.map(row => {
        const newRow: Record<string, any> = {}
        props.exportColumns?.forEach(col => {
          let value = row[col.prop]
          if (col.formatter) {
            value = col.formatter(value)
          }
          newRow[col.label] = value
        })
        return newRow
      })
    )

    const workbook = XLSX.utils.book_new()
    XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1')
    
    XLSX.writeFile(workbook, props.fileName)
    emit('export-success', exportData)
    ElMessage.success('导出成功')
  } catch (error: any) {
    emit('export-error', error)
    ElMessage.error(error.message || '导出失败')
  } finally {
    exporting.value = false
  }
}

// 读取Excel文件
const readExcelFile = (file: File): Promise<any[]> => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    
    reader.onload = (e: any) => {
      try {
        const data = new Uint8Array(e.target.result)
        const workbook = XLSX.read(data, { type: 'array' })
        const worksheet = workbook.Sheets[workbook.SheetNames[0]]
        const jsonData = XLSX.utils.sheet_to_json(worksheet)

        if (props.importColumns) {
          const processedData = jsonData.map(row => {
            const newRow: Record<string, any> = {}
            props.importColumns?.forEach(col => {
              let value = (row as any)[col.label]
              if (col.formatter) {
                value = col.formatter(value)
              }
              newRow[col.prop] = value
            })
            return newRow
          })
          resolve(processedData)
        } else {
          resolve(jsonData)
        }
      } catch (error) {
        reject(new Error('文件解析失败'))
      }
    }

    reader.onerror = () => {
      reject(new Error('文件读取失败'))
    }

    reader.readAsArrayBuffer(file)
  })
}
</script>

<style lang="scss" scoped>
.excel-handler {
  display: inline-flex;
  gap: 12px;
  align-items: center;

  .excel-button {
    height: 32px;
    padding: 0 16px;
    font-size: 14px;
    border-radius: 4px;
    font-weight: normal;
    background: #fff;
    border: 1px solid #dcdfe6;
    color: #606266;

    &:hover {
      color: #409eff;
      border-color: #c6e2ff;
      background-color: #ecf5ff;
    }

    &:active {
      color: #3a8ee6;
      border-color: #3a8ee6;
    }
  }

  .import-dialog {
    :deep(.el-dialog__body) {
      padding: 30px 24px;
    }

    .upload-area {
      width: 100%;
      :deep(.el-upload) {
        width: 100%;
      }
      :deep(.el-upload-dragger) {
        width: 100%;
        height: auto;
        padding: 40px 0;
      }
    }

    .upload-content {
      text-align: center;
    }

    .upload-text {
      margin-top: 16px;
      p {
        margin: 0;
        color: #606266;
        font-size: 14px;
        line-height: 1.6;

        em {
          color: #409eff;
          font-style: normal;
          cursor: pointer;
        }
      }

      .upload-tip {
        font-size: 12px;
        color: #909399;
        margin-top: 8px;
      }
    }

    .dialog-footer {
      margin-top: 24px;
      display: flex;
      justify-content: center;
      gap: 12px;

      .el-button {
        min-width: 100px;
      }
    }
  }
}
</style> 